﻿using GroupThreeMESProject.DTO;
using GroupThreeMESProject.Entity;
using GroupThreeMESProject.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using YamlDotNet.Core.Tokens;
using static Dm.net.buffer.ByteArrayBuffer;
using static Volo.Abp.Identity.Settings.IdentitySettingNames;

namespace GroupThreeMESProject.Service
{
    [ApiExplorerSettings(GroupName = "v2")]
    public class LoginService : ApplicationService
    {
        private readonly ISqlSugarClient _db;

        public LoginService(ISqlSugarClient db)
        {
            _db = db;
        }
        [HttpPost("Login/LoginUser")]
        public async Task<ApiResult<MesUser>> LoginUser(LoginRequestDto u)
        {
            var user = await _db.Queryable<MesUser>().Where(x => x.Account == u.name && x.UserPassword == u.pwd).FirstAsync();
            if (user == null)
            {
                return ApiResult<MesUser>.Error(message: "用户或密码错误");
            }
            else
            {
                return ApiResult<MesUser>.Success(user);

            }
        }
        [HttpGet("Login/UserList")]
        public async Task<ApiResult<FenYeDTO<MesUser>>> UserList(int pageIndex, int pageSize)
        {
            FenYeDTO<MesUser> fenYeDTO = new FenYeDTO<MesUser>();
            var list = await _db.Queryable<MesUser>().ToListAsync();
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(list.Count() * 1.0 / pageSize);
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            fenYeDTO.pageCount = pageCount;
            fenYeDTO.totalCount = totalCount;
            fenYeDTO.data = list;
            return ApiResult<FenYeDTO<MesUser>>.Success(fenYeDTO);
        }
        [HttpPost("Login/UserAdd")]
        public async Task<ApiResult<MesUser>> UserAdd(MesUser mesUser)
        {

            //这里需要注意的是，如果使用了Task.Run()就会导致 sql语句日志无法记录改成下面的
            var user = await Task.Run(() => _db.Insertable(mesUser).ExecuteCommand());
         
            if (user>0)
            {
                return ApiResult<MesUser>.Success(mesUser);
            }
            else
            {
                return ApiResult<MesUser>.Error(message: "添加失败");

            }

        }
    }
}
